import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
} from 'react-native';
import { useAuth } from '../profile/UserContext';
import { isValidPhoneNumber } from '../../utils/ValidationUtils';
import colors from '../../styles/colors';
import { t } from '../../i18n';
import { spacing } from '../../styles';
const LoginForm: React.FC = () => {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [isAgreed, setIsAgreed] = useState(false);
  const { isLoading, login } = useAuth();

  const handleLogin = async () => {
    if (!isValidPhoneNumber(phone)) {
      Alert.alert(t('common.prompt'), t('login.phone_error'));
      return;
    }

    if (password.length < 6) {
      Alert.alert(t('common.prompt'), t('login.password_error'));
      return;
    }

    if (!isAgreed) {
      Alert.alert(t('common.prompt'), t('login.agreement_error'));
      return;
    }

    try {
      await login({ phone, password });
    } catch (error) {
      console.error('Login failed:', error);
      Alert.alert(t('common.error'), t('login.user_or_password_error'));
    }
  };

  const handleRegister = () => {
    Alert.alert('提示', '注册功能待实现');
  };

  const toggleAgreement = () => {
    setIsAgreed(!isAgreed);
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder={t('login.phone_placeholder')}
          keyboardType="phone-pad"
          value={phone}
          onChangeText={setPhone}
          maxLength={11}
        />
      </View>

      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          placeholder={t('login.password_placeholder')}
          secureTextEntry
          value={password}
          onChangeText={setPassword}
          maxLength={20}
        />
      </View>

      <View style={styles.agreementContainer}>
        <TouchableOpacity
          onPress={toggleAgreement}
          style={styles.checkboxContainer}
        >
          <View style={[styles.checkbox, isAgreed && styles.checked]}>
            {isAgreed && <View style={styles.checkedInner} />}
          </View>
          <Text style={styles.agreementText}>
            {t('login.read_and_agree')}
            <Text style={styles.link}>《{t('login.terms_of_service')}》</Text>
            {t('common.and')}
            <Text style={styles.link}>《{t('login.privacy_policy')}》</Text>
          </Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity
        style={[styles.button, isLoading && styles.disabledButton]}
        onPress={handleLogin}
        disabled={isLoading}
      >
        <Text style={styles.buttonText}>
          {t(`${isLoading ? 'login.logining' : 'login.login'}`)}
        </Text>
      </TouchableOpacity>

      <View style={styles.registerContainer}>
        <Text style={styles.registerText}>{t('login.no_account')}</Text>
        <TouchableOpacity onPress={handleRegister}>
          <Text style={styles.registerLink}>{t('login.register_now')}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
    padding: spacing.padding.lg,
  },
  inputContainer: {
    marginBottom: spacing.margin.md,
  },
  input: {
    height: 50,
    borderWidth: 1,
    borderColor: colors.border.primary,
    borderRadius: 8,
    paddingHorizontal: spacing.padding.md,
    backgroundColor: colors.surface,
  },
  agreementContainer: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: spacing.margin.lg,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderRadius: 4,
    borderWidth: 1,
    borderColor: colors.border.secondary,
    marginRight: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checked: {
    borderColor: colors.primary,
    backgroundColor: colors.primary,
  },
  checkedInner: {
    width: 10,
    height: 10,
    backgroundColor: colors.white,
    borderRadius: 2,
  },
  agreementText: {
    flex: 1,
    fontSize: 14,
    color: colors.text.secondary,
    lineHeight: 20,
  },
  link: {
    color: colors.primary,
  },
  button: {
    backgroundColor: colors.primary,
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: spacing.margin.md,
  },
  disabledButton: {
    backgroundColor: colors.grey,
  },
  buttonText: {
    color: colors.primaryButtonText,
    fontSize: 16,
    fontWeight: 'bold',
  },
  registerContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  registerText: {
    color: colors.text.tertiary,
    marginRight: 4,
  },
  registerLink: {
    color: colors.primary,
    fontWeight: 'bold',
  },
});

export default LoginForm;
